import os
import threading
from typing import List

from sqlalchemy import text
from utils import _db, safe_load_dotenv
from dotenv import load_dotenv

safe_load_dotenv("./config/.env")
URL = os.getenv("database.uri")


def gen_table_model(tablename):
    # Ensure output directory exists
    os.makedirs("./models", exist_ok=True)
    import subprocess

    cmd = f"sqlacodegen {URL} --tables {tablename} --outfile  ./models/{tablename}.py"
    out = subprocess.run(cmd, shell=True, capture_output=True, text=True)
    print(out)


if __name__ == "__main__":

    table_list = [
        "casbin_rule",
        "casbin_rule_path",
    ]
    print(table_list)

    threads: List[threading.Thread] = []
    for table in table_list:
        threads.append(threading.Thread(target=gen_table_model, args=(table,)))
    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join()
